package com.yc.chatroom.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

@Component
public class ServerManager {
	
	@Autowired
	private ServerHandler serverHandler;
	
	/**
	 * 启动服务端
	 * @param port
	 */
	public void start(int port) {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workGroup = new NioEventLoopGroup();
		
		try {
			ServerBootstrap b = new ServerBootstrap();//服务端辅助启动类
			b.group(bossGroup, workGroup)
				.channel(NioServerSocketChannel.class)
				.option(ChannelOption.SO_BACKLOG, 100)
				.childHandler(new ChildrenChannelHandler());
			
			ChannelFuture f = b.bind(port).sync();//sync是确保前面的配置都已经做完，让下面这句输出语句不是一句空话
			System.out.println("---------服务端开始监听端口-" + port);
			
			f.channel().closeFuture().sync();//阻塞等待关闭信号
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workGroup.shutdownGracefully();
		}
		
		
		
	}
	
	class ChildrenChannelHandler extends ChannelInitializer<SocketChannel> {

		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			//设置解码器
			ch.pipeline().addLast(new ObjectDecoder(100*100, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
			ch.pipeline().addLast(new ObjectEncoder());//设置编码器
			ch.pipeline().addLast(serverHandler);
		}
		
	}

	public static void main(String[] args) {
		new ServerManager().start(8787);

	}

}
